#!/usr/bin/env python3

FORBIDDEN = 'THIS IS SOLUTION CODE'

# bash 1-liner that doesn't work. It always exits with status 1, though it does
# print the message when the forbidden string is found
#git diff --cached --name-only | xargs grep --with-filename -n "$FORBIDDEN" && echo "COMMIT REJECTED Found '$FORBIDDEN' in files to be committed." && exit 1


import subprocess, os, sys

def has_forbidden_string(file_path, forbidden_string):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            contents = file.read()
            return forbidden_string in contents
    except (UnicodeDecodeError, IsADirectoryError):
        # ignore binary files, directories
        return False
    return False
    
def main():
    # Run 'git diff --cached --name-only' to get a list of staged files
    result = subprocess.run(['git', 'diff', '--cached', '--name-only'], capture_output=True, text=True, check=True)
    staged_files = result.stdout.strip().split('\n')

    # Check each staged file for the forbidden string
    for file_path in staged_files:
        if os.path.isfile(file_path) and has_forbidden_string(file_path, FORBIDDEN):
            print(f"Error: Commit aborted. File {file_path} contains the forbidden string '{FORBIDDEN}'.")
            exit(1)
            pass
        pass
    pass

if __name__ == "__main__":
    main()
    # if we reach here, exit with 0 status
